Mongo - MapReduce
Lesson Objectives
- Explain what MapReduce is and why we have it
- Explain structure of Map Reduce
- Explain map function
- Explain reduce function
- Explain aggregating multiple values
- Explain Multiple group by
Explain what MapReduce is and why we have it
Explain structure of Map Reduce
- db.collectionName.mapReduce(mapFunction, reduceFunction, { query: {}, out:{} })
- out
- collection name
- { [ replace | inline | merge | reduce ]: 1 }
Explain map function
- return key=>value pair
const emitter = function () {
if (this.gender === "m") {
emit(this.name, { yum: this.loves[0], weight: this.weight });
}
};
db.employees.mapReduce(emitter, function () {}, { out: "mapTest" });
Explain reduce function
- if multiple values for a key, how to reduce
const emitter = function () {
emit(this.gender, this.weight);
};
const reducer = (key, values) => Array.sum(values);
db.employees.mapReduce(emitter, reducer, { out: "mapTest" });
Multiple values
const emitter = function () {
emit(this.gender, { weights: this.weight, money: this.salary });
};
const reducer = (key, values) => {
let total_weight = 0;
let total_salary = 0;
for (let i = 0; i < values.length; i++) {
total_weight += values[i].weights;
total_salary += values[i].money;
}
return { total_weight: total_weight, total_salary: total_salary };
};
db.employees.mapReduce(emitter, reducer, { out: "mapTest" });
db.mapTest.find();
Multiple group by
const emitter = function () {
emit(
{
gender: this.gender,
weight: this.weight,
},
this.weight
);
};